<template>
  <div
    class="container"
    style="height: 100%; width: 100%;"
  >
    <div
      ref="chart"
      style="height: 100%; width: 100%;"
      @mouseover="stop"
      @mouseout="start"
    >
    </div>
    <div
      ref="mask"
      class="mask"
    >
      <div
        class="close"
        @click="close"
      >关闭</div>
    </div>

  </div>
</template>

<script>
import * as echarts from 'echarts'
export default {
  name: 'EchartsBar1Wrap',
  /**
   * xData x坐标值
   * yData y轴坐标
   * lineColor: 折线图颜色
   * type: 图表类型
   * areaColor 渐变色---nomarl正常色, unique: 单独设置特殊色
   * unit 纵轴单位
   * title: 标题
   * legend: name: 图例名称 color: 表示颜色
   * toolTip: color: 背景色;type: 种类(根据项目所需传值)
   * contrast: 对比规则 true/false true表示数据a>b 反之 a<b
   * contrastData: 对比数据
   *    */
  props: {
    xData: {
      type: Array,
      default: () => {
        return ['2017', '2018', '2019', '2020', '2021']
      }
    },
    yData: {
      type: Array,
      default: () => {
        return [
          [1, 4, 8, 3, 4],
          [2, 4, 6, 4, 3],
          [20, 40, 80, 30, 40]
        ]
      }
    },
    type: {
      type: Array,
      default: () => ['bar', 'bar', 'line']
    },
    // 可修改项
    lineColor: {
      type: String,
      default: 'rgba(252, 169, 62, 1)'
    },
    areaColor: {
      type: Array,
      default: () => [
        ['RGBA(18, 142, 232, 1)', 'RGBA(18, 142, 232, .3)'],
        ['rgba(25, 194, 147, 1)', 'rgba(25, 194, 147, .3)']
      ]
    },
    color: {
      type: Array,
      default: () => [
        'RGBA(18, 142, 232, 1)',
        'rgba(25, 194, 147, 1)',
        'rgba(252, 169, 62, 1)'
      ]
    },
    title: {
      type: String,
      default: ''
    },
    unit: {
      type: String,
      default: ''
    },
    legend: {
      type: Array,
      default: () => ['计划', '实际', '同比']
    },
    toolTip: {
      type: Object,
      default: () => {
        return {
          color: ''
        }
      }
    },
    contrast: {
      type: Boolean,
      default: true
    },
    actualData: {
      type: Array,
      default: () => [
        [1, 4, 8, 3, 4],
        [2, 4, 6, 4, 3]
      ]
    },
    planData: {
      type: Array,
      default: () => [
        [1, 4, 8, 3, 4],
        [2, 4, 6, 4, 3]
      ]
    }
  },

  data () {
    return {
      chart: null,
      option: null,
      timer: null,
      max: 0,
      min: 0,
      seriesDatas: [],
      index: 0,
      maskShow: false
    }
  },

  watch: {
    // 监听index变化实现自动切换
    index: {
      handler (i) {
        if (this.xData && i < this.xData.length) {
          this.$nextTick(() => {
            this.changeAuto(i)
          })
        } else {
          this.index = 0
        }
      },
      immediate: true
    }
  },

  created () {
    // 初始化图表数据
    this.seriesData()
  },

  mounted () {
    // 初始化图表
    this.$nextTick(() => {
      this.convertData()
      this.init()
      this.chart.resize()
    })
  },

  beforeDestroy () {
    // 销毁定时器
    clearTimeout(this.timer)
    // 销毁图表实例
    // this.chart.dispose()
  },

  methods: {
    seriesData () {
      const arr = []
      const areaColor = this.areaColor
      const color = this.color
      const that = this
      this.yData.forEach((item, i, ary) => {
        arr.push({
          name: this.legend[i],
          type: that.type[i],
          yAxisIndex: that.type[i] === 'line' ? 1 : 0,
          barWidth: 12,
          showSymbol: true,
          symbolSize: 5,
          animationDuration: 2000,
          label: {
            show: false,
            fontSize: 13,
            position: 'top',
            color: '#666666',
            fontFamily: 'Microsoft YaHei'
          },
          lineStyle: {
            color: this.lineColor
          },
          color: color[i],
          itemStyle: {
            normal: {
              color: function (params) {
                if (params.componentSubType === 'bar') {
                  return new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    {
                      offset: 0,
                      color: areaColor[i][0]
                    },
                    {
                      offset: 1,
                      color: areaColor[i][1]
                    }
                  ])
                } else {
                  return that.lineColor
                }
              }
            }
          },
          data: ary[i].map((item) => item)
        })
      })
      this.seriesDatas = arr
    },
    init () {
      this.chart = echarts.init(this.$refs.chart)
      const unit = this.unit
      this.option = {
        title: {
          text: `${this.title}`,
          x: 'center',
          textStyle: {
            color: '#fff',
            fontSize: 13,
            fontWeight: 400,
            fontFamily: 'PingFangMedium'
          },
          textAlign: 'left'
        },
        grid: {
          left: '0',
          right: '0',
          bottom: '0',
          top: '35',
          containLabel: true
        },
        legend: {
          show: true,
          x: 'center',
          textStyle: {
            fontSize: 13,
            color: '#666'
          },
          itemWidth: 16,
          itemHeight: 7
        },
        tooltip: {
          trigger: 'axis',
          borderWidth: 1,
          borderRadius: 12,
          padding: 0,
          confine: true,
          axisPointer: {
            type: 'shadow',
            lineStyle: {}
          },
          formatter: function (params, ticket, callback) {
            let res = ''
            res = `<div  style="background: linear-gradient(135deg,#EEF2F5, rgba(250,252,253,0.5));padding: 11px 16px;
                   border: 1px solid #FFFFFF;border-radius: 12px;">
                  <div style="font-size: 15px;font-family: Microsoft YaHei;font-weight: 400;color: #333333;margin-bottom: 4px">${
                    params[0].name
                  }</div>
                  ${params
                    .map((item, index, arr) => {
                      return `
                    <div style="display: flex;justify-content: space-between">
                     <div><span style="display:inline-block;margin-right:5px;border-radius:10px;width:8px;height:8px;background-color:${
                       item.componentSubType === 'bar'
                         ? item.color.colorStops[0].color
                         : item.color
                     };border: 2px solid #fff"};></span><span style="font-size: 15px;font-family: Microsoft YaHei;font-weight: 400;color: #666666;">${
                        item.seriesName
                      }</span></div>
                     <div style="margin-left: 19px"><span style="font-size: 15px;font-family: FZZhengHeiS-EB-GB;font-weight: 400;color: #666666;">${
                       item.data
                     }</span><span style="font-size: 12px;font-family: Microsoft YaHei;font-weight: 400;color: #666666;">台</span></div>
                    </div>`
                    })
                    .join('')}
                  </div>`
            return res
          }
        },
        xAxis: {
          type: 'category',
          triggerEvent: true,
          axisLine: {
            lineStyle: {
              color: 'rgba(237, 239, 242, 1)'
            }
          },
          axisTick: {
            show: true,
            lineStyle: {}
          },
          axisLabel: {
            fontSize: 16,
            color: '#666666',
            fontFamily: 'Microsoft YaHei'
            // formatter: function (value, index) {
            //   console.log(value, index, data, 'index')
            //   const icon = (index == (xdata.length - 1) ? 'First' : index == (xdata.length - 2) ? 'Second' : index == (xdata.length - 3) ? 'Thrid' : 'Other')
            //   if (icon == 'Other') {
            //     return '{' + icon + '|' + (xdata.length - index) + ' }' + value + ''
            //   }
            //   return '{' + icon + '| }{value|' + value + '}'
            // }
          },
          data: this.xData
        },
        yAxis: [
          {
            type: 'value',
            name: `${unit}`,
            axisLabel: {
              textStyle: {
                fontSize: 16,
                color: '#666666',
                fontFamily: 'Microsoft YaHei'
              }
            },
            axisLine: {
              show: false
            },
            splitLine: {
              show: true,
              lineStyle: {
                color: 'rgba(237, 239, 242, 1)'
              }
            },
            axisTick: {
              show: false
            }
          },
          {
            type: 'value',
            show: false,
            min: 0,
            max: 100,
            interval: 20,
            axisTick: {
              show: false
            },
            axisLine: {
              lineStyle: {}
            },
            axisLabel: {
              show: false,
              formatter: '{value}%'
            }
          }
        ],
        series: this.seriesDatas
      }
      this.chart.clear(this.option)
      this.chart.setOption(this.option)
      const that = this
      window.addEventListener('resize', function () {
        that.chart.resize()
      })
      // that.chart.on('mouseover', function (params) {
      //   clearTimeout(that.timer)
      // })
      // that.chart.on('mouseout', function (params) {
      //   clearTimeout(that.timer)
      //   that.changeAuto(that.index)
      this.chart.on('click', function (params) {
        if (params.componentType === 'xAxis') {
          console.log('单击了' + params.value + 'x轴标签')
          that.maskShow = true
          that.$refs.mask.style.opacity = 1
          that.$refs.mask.style.zIndex = 1000
        } else {
          console.log('单击柱状图')
          // that.$refs.mask.style.opacity = 0
        }
      })
    },
    changeAuto (i) {
      const that = this
      that.timer = setTimeout(function () {
        if (that.index < that.xData.length) {
          that.chart.dispatchAction({
            type: 'showTip',
            seriesIndex: 0,
            dataIndex: that.index
          })
          that.index++
        } else {
          that.index = 0
        }
      }, 2000)
    },
    start () {
      this.changeAuto(this.index)
    },
    stop () {
      clearTimeout(this.timer)
    },
    formatterData () {},
    convertData () {
      const arrLen = this.planData.length
      for (let i = 0; i < arrLen - 1; i++) {
        for (let j = 0; j < this.actualData[i].length; j++) {
          if (this.actualData[i][j] > this.planData[i][j]) {
            this.xData.forEach((item, idx, arr) => {
              if (idx === j) {
                this.$emit(
                  'changeData',
                  idx,
                  this.planData[idx],
                  this.actualData[idx]
                )
              }
            })
          }
        }
      }
    },
    close () {
      this.$refs.mask.style.zIndex = -1
      this.$refs.mask.style.opacity = 0
      this.$refs.chart.style.opacity = 1
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  position: relative;
}
.show {
  opacity: 0.6;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 10;
}
.mask {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  background-color: rgba(0, 0, 0, 0.6);
  z-index: -1;
  opacity: 0;
  transition: opacity 0.5s ease-in;
}
.close {
  color: #fff;
  display: flex;
  justify-content: flex-end;
  padding: 6px 10px;
  cursor: pointer;
}
</style>
